package iotapp

import (
	"gitee.com/captials-team/ubdframe/src/apps"
	httpController "gitee.com/captials-team/ubdframe/src/apps/iotapp/controllers/http"
	"gitee.com/captials-team/ubdframe/src/apps/iotapp/docs"
	"gitee.com/captials-team/ubdframe/src/common"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	"gitee.com/captials-team/ubdframe/src/domain/interfaces"
	"gitee.com/captials-team/ubdframe/src/pkg/gin_http"
	"gitee.com/captials-team/ubdframe/src/pkg/jwtauth"
	v1log "gitee.com/captials-team/ubdframe/src/pkg/logs"
	"gitee.com/captials-team/ubdframe/src/pkg/uber_help"
	"github.com/gin-gonic/gin"
	"go.uber.org/dig"
)

type ApiServer struct {
	di   *dig.Container
	conf *configstc.IotAppConfig
	*apps.ApiServer

	gin_http.SwaggerOption //swagger相关选项配置
	gin_http.PProfOption   //pprof选项配置

	AdminAuthOption gin_http.AuthOption //auth相关选项配置
}

func (s *ApiServer) Name() string {
	return "user_api"
}

func (s *ApiServer) InitRouter() {
	s.Engine().GET("ping", gin_http.PingHandler)
	s.InitRouterForGin(s.Engine())
}

func (s *ApiServer) InitRouterForGin(engine *gin.Engine) {
	var g = engine.Group("")
	if len(s.conf.RoutePrefix) > 0 {
		g = engine.Group(s.conf.RoutePrefix)
	}

	//注册swagger
	s.SwaggerRouter(g)

	//注册pprof
	s.PProfRouter(engine)

	s.router(g)

	return
}

func (s *ApiServer) router(g gin.IRouter) {
	g.Use(
		gin_http.PanicHandler,
		gin_http.QPSLimiterHandler(10, 10),
	)
	adminGroup := g.Group("", s.AdminAuthOption.OptAuthHandler())

	//后台模块
	common.ErrPanic(s.di.Invoke(func(ctr interfaces.ItfTelemetryController) {
		adminGroup.POST("/mag/telemetry/latest", ctr.GetLatest)      //最新测点数据
		adminGroup.POST("/mag/telemetry/history", ctr.SearchHistory) //历史数据
		adminGroup.POST("/mag/telemetry/stats", ctr.SearchStats)     //统计数据
	}))
}

func (s *ApiServer) Start() error {
	if !s.Module() {
		s.InitRouter()
	}
	return s.ApiServer.Start()
}

func (s *ApiServer) Stop() error {
	return s.ApiServer.Stop()
}

func NewApiServer(di *dig.Container, conf *configstc.IotAppConfig, logger v1log.ILog) *ApiServer {
	common.ErrPanic(di.Provide(httpController.NewTelemetryController, dig.As(new(interfaces.ItfTelemetryController))), uber_help.ErrAlreadyProvided)

	docs.SwaggerInfoiotserevice.Host = conf.ApiServer.HostAddr() + conf.RoutePrefix

	s := &ApiServer{
		di:   di,
		conf: conf,
		SwaggerOption: gin_http.SwaggerOption{
			Enable:  conf.DocsEnable,
			Name:    docs.SwaggerInfoiotserevice.InstanceName(),
			Swagger: docs.SwaggerInfoiotserevice,
		},
		PProfOption: gin_http.PProfOption{
			Enable: conf.PProfEnable,
		},
		ApiServer: apps.NewApiServer(gin.Default(), conf.ApiServer),
	}

	s.ApiServer.WithCors()

	//管理端auth
	s.AdminAuthOption.AuthHandler = gin_http.AuthHandler(jwtauth.NewJwtTokenHandler(conf.AuthConfig.SecretKey))

	return s
}
